"""
python read_4_json.py
"""

"""

    这个模块有几个可以直接用的函数，可以不需要传参数，已经指定好了默认路径
    
    直接from read_4_json import * 即可
    
    下面的四个函数的返回值 都是dict数组类型，
    下面是示例：
    
    print(warehouses[0])
    print(average_inventory[0])
    print(average_sales[0])
    print(association_data[0])
    
    print("------")
    print(type(warehouses))
    print(type(warehouses[0]))
    
    
    {'warehouse_id': 1, 'max_inventory': 618887, 'max_sales': 20310, 'daily_cost': 1826.329572}
    {'category_id': 1, 'average_inventory': 6215.368614331114}
    {'category_id': 1, 'average_sales': 29.406202582728053}
    {'category1': 157, 'category2': 195, 'association': 103}
    ------
    <class 'list'>
    <class 'dict'>

"""

"""    
    然后像这样使用：
    
    import read_4_json as r4j

    # 这四个都是dict 数组
    data_warehouse = r4j.load_warehouse_data()
    data_category_inventory = r4j.load_average_inventory_data()
    data_category_sales = r4j.load_average_sales_data()
    data_category_assotication = r4j.load_association_data()
    mx_category_association = r4j.create_adjacency_matrix()
    # 这个mx是矩阵
    
    # 这两个是常量
    NUM_W = r4j.NUM_W
    NUM_C = r4j.NUM_C
    

"""

import json
import os
import re
import numpy as np

NUM_W = 140
NUM_C = 350

# 定义文件路径
WAREHOUSE_JSON_PATH = os.path.join("..", "fujian", "fujian3", "origin_data", "warehouse.json")
INVENTORY_FILE_PATH = os.path.join("..", "fujian", "fujian3", "data_from_p1", "all_average_inventory.json")
SALES_FILE_PATH     = os.path.join("..", "fujian", "fujian3", "data_from_p1", "all_average_sales.json")
ASSOCITAION_FILE_PATH = os.path.join("..", "fujian", "fujian4", "origin_data.json")

# 读取 JSON 数据并转换为 Python 对象数组
def load_warehouse_data(file_path = WAREHOUSE_JSON_PATH):
    with open(file_path, 'r', encoding='utf-8') as file:
        warehouse_data = json.load(file)  # 读取并解析 JSON 数据

    # 提取 warehouse_id 中的数字并转换为整数
    for warehouse in warehouse_data:
        match = re.search(r'warehouse(\d+)', warehouse["warehouse_id"])
        if match:
            warehouse["warehouse_id"] = int(match.group(1))  # 转换为整数

    warehouse_data.sort(key=lambda x: x['warehouse_id'])
    return warehouse_data


# 定义读取商品品类库存量均值的函数
def load_average_inventory_data(file_path = INVENTORY_FILE_PATH):
    with open(file_path, 'r', encoding='utf-8') as file:
        average_inventory_data = json.load(file)  # 读取并解析 JSON 数据
    for item in average_inventory_data:
        item['category_id'] = int(item['category_id'])  # 转换为整数类型
    average_inventory_data.sort(key=lambda x: x['category_id'])
    return average_inventory_data

# 定义读取商品品类销售量均值的函数
def load_average_sales_data(file_path = SALES_FILE_PATH):
    with open(file_path, 'r', encoding='utf-8') as file:
        average_sales_data = json.load(file)  # 读取并解析 JSON 数据
    for item in average_sales_data:
        item['category_id'] = int(item['category_id'])  # 转换为整数类型 
    average_sales_data.sort(key=lambda x: x['category_id'])  # 按 category_id 排序
    return average_sales_data

# 定义读取商品关联度信息的函数
def load_association_data(file_path = ASSOCITAION_FILE_PATH):
    with open(file_path, 'r', encoding='utf-8') as file:
        association_data = json.load(file)  # 读取并解析 JSON 数据
    
    # 使用正则提取数字，并构建新的列表
    processed_data = []
    for item in association_data:
        # 提取类别数字
        category1 = int(re.search(r'\d+', item['category1']).group())
        category2 = int(re.search(r'\d+', item['category2']).group())
        association_value = item['association']
        
        # 将提取后的信息加入处理后的列表
        processed_data.append({
            'category1': category1,
            'category2': category2,
            'association': association_value
        })
    
    # processed_data.sort
    return processed_data

# 定义构建邻接矩阵的函数
# def create_adjacency_matrix(association_data, num_categories=350):
def create_adjacency_matrix():
    association_data = load_association_data()
    
    # 创建一个全零的邻接矩阵
    adjacency_matrix = np.zeros((NUM_C, NUM_C))

    # 遍历关联度数据，填充邻接矩阵
    for item in association_data:
        category1 = item['category1']-1  # 直接使用已处理的类别
        category2 = item['category2']-1  # 直接使用已处理的类别
        association_value = item['association']
        
        # print(category1, ", ", category2)

        # 填充矩阵（双向边）
        adjacency_matrix[category1][category2] = association_value
        adjacency_matrix[category2][category1] = association_value

    return adjacency_matrix

def split3(data):
    """
    按照 category_id 从小到大排序，并将每个字典拆分为三个部分。

    :param data: 包含字典的列表，每个字典有 'category_id' 和其他数值字段
    :return: 拆分后并排序的字典列表
    """
    # 按照 category_id 排序
    sorted_data = sorted(data, key=lambda x: x['category_id'])

    result = []
    for entry in sorted_data:
        category_id = entry['category_id']
        # 拆分成三个新字典
        for i in range(3):
            new_entry = entry.copy()  # 复制原字典
            new_entry['category_id'] = 3 * category_id - (2 - i)  # 计算新的 category_id
            for key in entry:
                if key != 'category_id':
                    new_entry[key] /= 3  # 将其他字段的值变成原先的三分之一
            result.append(new_entry)

    return result


"""
python read_4_json.py

"""

if __name__ == "__main__":
    print("in main()")
    
    # warehouses = load_warehouse_data()
    # print(warehouses)
    
    # average_inventory = load_average_inventory_data()
    # average_sales = load_average_sales_data()
    # print("商品品类库存量均值：", average_inventory)
    # print("商品品类销售量均值：", average_sales)


    # # 读取关联度数据
    # association_data = load_association_data()
    # # print(association_data)

    # adjacency_matrix = create_adjacency_matrix()
    # print("邻接矩阵：")
    # print(adjacency_matrix)
    # cnt = 0
    # for i in range(adjacency_matrix.shape[0]):  # 遍历行
    #     for j in range(adjacency_matrix.shape[1]):  # 遍历列
    #         x = adjacency_matrix[i][j]
    #         if ( x!=0 ):
    #             print(f"Element at position ({i}, {j}): {x}")
    #             cnt += 1
    
    # print("none zero cnt = ", cnt)
    
    
    # warehouses = load_warehouse_data(WAREHOUSE_JSON_PATH)
    # average_inventory = load_average_inventory_data(INVENTORY_FILE_PATH)
    # average_sales = load_average_sales_data(SALES_FILE_PATH)
    # association_data = load_association_data(ASSOCITAION_FILE_PATH)
    # adjacency_matrix = create_adjacency_matrix()

    # print(warehouses[0])
    # print(average_inventory[0])
    # print(average_sales[0])
    # print(association_data[0])
    
    # print("------")
    # print(type(warehouses))
    # print(type(warehouses[0]))
    
    # print(warehouses)
    # print(average_inventory)
    # print(average_sales)
    # print(association_data)
    # print(adjacency_matrix)
    
    
    # 示例用法
    # data = [
    #     {'category_id': 1, 'average_inventory': 6215.368614331114},
    #     {'category_id': 2, 'average_inventory': 1500.0},
    # ]

    # result = split3(data)
    # print(result)
    
    average_inventory = load_average_inventory_data(INVENTORY_FILE_PATH)
    res = split3(average_inventory)

    print(average_inventory)
    # print(res)
    
    print("main() ended.")
    
    

"""
python read_4_json.py
"""

    


